import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../components/app_conifg.dart';
import '../../../utils/EventMgr.dart';
import '../../../utils/logger.dart';

///我的订单控制器
class MyOrderController extends BaseController with SingleGetTickerProviderMixin {
  late TabController statusTabController;

  final ScrollController scrollController = ScrollController();

  final TextEditingController searchTxt = TextEditingController();

  int page = 1;

  /// 订单类型 类型 0全部 1代付款 2待收货 3取消 4已完成 5未评价 6已评价 7售后 8售后记录 9待发货
  int type = 0;

  int initTabIndex = 0;

  String keyWord = '';

  bool hasNextPage = true;

  ///订单列表
  List orderList = [];

  bool showOldOrder = false;

  @override
  void onEventBus() {
    super.onEventBus();

    ///监听路由
    EventMgr.on(EventType.refreshOrderList, (arg) {
      getMyorderLists();
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onInit() {
    if (Get.arguments != null) {
      int ctype = Get.arguments['type'] ?? 0;
      type = ctype;
      switch (type) {
        case 1:
          initTabIndex = 1;
          break;
        case 2:
          initTabIndex = 3;
          break;
        case 9:
          initTabIndex = 2;
          type = 9;
          break;
        default:
      }
    }
    getMyorderLists();

    getDefaultInfoConfig();

    //---------订单状态---------
    statusTabController = TabController(length: 6, vsync: this, initialIndex: initTabIndex);
    statusTabController.addListener(() {
      page = 1;
      // scrollToTopSmooth();
      if (statusTabController.indexIsChanging) {
        // 当tab切换时执行的操作
        switch (statusTabController.index) {
          case 0:
            type = 0;
            break;
          case 1:
            type = 1;
            break;
          case 2:
            type = 9;
            break;
          case 3:
            type = 2;
            break;
          case 4:
            type = 3;
            break;
          case 5:
            type = 4;
            break;
          default:
        }
        getMyorderLists();
      }
    });
    super.onInit();
  }

  //获取我的订单列表
  getMyorderLists() {
    Tools.showLoading();
    Network.getMyOrderList(
      type,
      page,
      10,
      keyword: keyWord != '' ? keyWord : '',
    ).then((value) {
      print(value['list']);
      if (page == 1) {
        orderList = value['list'];
      } else {
        orderList.addAll(value['list']);
      }
      hasNextPage = value['hasNextPage'];
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///再来一单
  void argin(List goodsInfo, int type) {
    Tools.showModal(
        content: "确定要再来一单么?",
        onCancel: (tag) => {},
        onConfirm: (tag) {
          Map<String, dynamic> params = {};
          params['type'] = type;
          params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
          params['goodsList'] = getPlaceOrderGoodsList(goodsInfo);
          params['sid'] = AppData.sid;
          params['addressId'] = '';
          SmartDialog.dismiss(tag: tag);
          Get.toNamed(Routes.fillOrder, arguments: params);
        });
  }

  /// deleteOrder
  void deleteOrder(String orderId) {
    Tools.showLoading();
    Network.deleteOrder(orderId).then((value) {
      if (value) {
        onPageRefresh();
        update();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///取消订单
  void cancelOrder(String orderId) {
    Tools.showModal(
        content: "确定要取消该订单么?",
        onCancel: (tag) => {},
        onConfirm: (tag) {
          Tools.showLoading();
          Network.cancelOrder(orderId).then((value) {
            if (value) {
              SmartDialog.dismiss(tag: tag);
              Tools.showToast("已取消");
              onPageRefresh();
              update();
            }
            Tools.hideLoading();
          }).catchError((error) {
            Tools.hideLoading();
          });
        });
  }

  ///下单商品列表
  List<Map<String, dynamic>> getPlaceOrderGoodsList(List goodsInfo) {
    List<Map<String, dynamic>> arr = [];

    goodsInfo.forEach((goods) {
      Map<String, dynamic> info = {};
      info['buyNum'] = goods['buyNum'];
      info['goodsId'] = goods['goodsId'];
      info['isSelect'] = 1;
      info['isSend'] = goods['isSend'];
      info['specNum'] = goods['specNum'];
      arr.add(info);
    });
    return arr;
  }

  ///确认收货
  receive(String orderId) {
    Tools.showLoading();
    Network.receive(orderId).then((value) {
      if (value) {
        Tools.showToast("收货成功");
        EventMgr.send(EventType.refreshOrderList);
        EventMgr.send(EventType.refreshLogin);
        // getMyorderLists();
        // update();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///售后确认收货
  orderReturnReceive(String orderId) {
    Tools.showLoading();
    Network.orderReturnReceive(orderId).then((value) {
      if (value) {
        Tools.showToast("收货成功");
        EventMgr.send(EventType.refreshOrderList);
        EventMgr.send(EventType.refreshLogin);
        getMyorderLists();
        update();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //搜索
  void search(String keyword) {
    page = 1;
    type = 0;
    keyWord = keyword;
    getMyorderLists();
    update();
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page = 1;
    await getMyorderLists();
    // 完成下拉刷新，并重置 footer 状态
    baseRefreshCtr.refreshCompleted(resetFooterState: !hasNextPage);
    // 根据是否有更多数据来设置 footer 的状态
    if (hasNextPage) {
      baseRefreshCtr.resetNoData(); // 重置为上拉加载状态
    } else {
      baseRefreshCtr.loadNoData(); // 显示 "没有更多数据"
    }
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (hasNextPage) {
      page += 1;
      await getMyorderLists();
      baseRefreshCtr.loadComplete();
    } else {
      baseRefreshCtr.loadNoData();
    }
  }

  @override
  void onClose() {
    statusTabController.dispose();
    scrollController.dispose();
    EventMgr.off(EventType.refreshOrderList);
    super.onClose();
  }

  // 平滑滚动到顶部
  void scrollToTopSmooth() {
    scrollController.animateTo(
      0.0, // 滚动到顶部的位置
      duration: const Duration(milliseconds: 300), // 动画持续时间
      curve: Curves.easeInOut, // 滚动曲线
    );
  }

  /// 是否展示会员模块
  Future getDefaultInfoConfig() async {
    await Network.getDefaultInfo().then((value) {
      showOldOrder = value['showOldOrder'] == 1;
      update();
    }).catchError((error) {});
  }

  void goToBdHistoryOrders() {
    Network.getBdOrderGetUrl().then((value) {
      String urlString = value;
      launchUrl(Uri.parse(urlString));
    });
  }
}
